package com.zhangjingcheng.yunyixia.util;

import com.zhangjingcheng.yunyixia.constant.MessageConstant;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.ObjectCannedACL;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;

import java.net.URI;

@Data
@AllArgsConstructor
@Slf4j
public class S3UploadUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String region;

    public String upload(byte[] bytes, String objectName) {
        // 在objectName前添加yunyi-xia文件夹路径
        String folderPath = "yunyi-xia/";
        String fullObjectName = folderPath + objectName;
        
        log.info("region: {}", region);
        log.info("endpoint: {}", endpoint);
        log.info("url:{}", URI.create(endpoint));
        // 创建S3Client实例
        S3Client s3Client = S3Client.builder()
                .endpointOverride(URI.create(endpoint)) // 自定义端点
                .credentialsProvider(StaticCredentialsProvider.create(
                        AwsBasicCredentials.create(accessKeyId, accessKeySecret)
                ))
                .region(Region.of(region)) // 区域
                .forcePathStyle(true)      // 强制 Path-style 请求（必须开启）
                .build();

        try {
            // 创建PutObject请求
            s3Client.putObject(
                    PutObjectRequest.builder()
                            .bucket(bucketName)
                            .key(fullObjectName)
                            .acl(ObjectCannedACL.PUBLIC_READ)
                            .build(),
                    RequestBody.fromBytes(bytes)
            );
        } catch (Exception e) {
            log.error("上传文件到S3失败", e);
            throw new RuntimeException(MessageConstant.UPLOAD_FAILED, e);
        }

        // 文件访问路径规则 https://BucketName.Endpoint/ObjectName
        return String.format("%s/%s/%s", endpoint, bucketName, fullObjectName);
    }

    /**
     * 从S3存储中删除文件
     * @param fullPath 文件完整访问路径
     * @return 删除是否成功
     */
    public boolean delete(String fullPath) {
        try {
            // 从完整路径中提取objectName
            // 完整路径格式: https://endpoint/bucketName/yunyi-xia/objectName
            String prefix = String.format("%s/%s/", endpoint, bucketName);
            String fullObjectName = fullPath.substring(fullPath.indexOf(prefix) + prefix.length());
            
            // 创建S3Client实例
            S3Client s3Client = S3Client.builder()
                    .endpointOverride(URI.create(endpoint)) // 自定义端点
                    .credentialsProvider(StaticCredentialsProvider.create(
                            AwsBasicCredentials.create(accessKeyId, accessKeySecret)
                    ))
                    .region(Region.of(region)) // 区域
                    .forcePathStyle(true)      // 强制 Path-style 请求（必须开启）
                    .build();

            // 创建DeleteObject请求
            s3Client.deleteObject(
                    DeleteObjectRequest.builder()
                            .bucket(bucketName)
                            .key(fullObjectName)
                            .build()
            );
            return true;
        } catch (Exception e) {
            log.error("从S3删除文件失败", e);
            throw new RuntimeException(MessageConstant.DELETE_FAILED);
        }
    }
}
